import 'dart:typed_data';
import 'package:crypto/crypto.dart';
import 'package:encrypt/encrypt.dart';
import 'my_global.dart';

/// 获取字符串格式数据
/// 因某些接口会有动态属性字段，所以产生了此方法......
/// [value] 要判断的值
/// [defaultValue] 当[value]值无法解析时，默认返回的值
String getStringFormat(dynamic value, {String defaultValue = ""}) {
  if (value is String) {
    return value.isNotEmpty ? value : defaultValue;
  } else if (value is Map) {
    if (value.isNotEmpty) {
      return value[value.keys.toList().first];
    } else {
      return defaultValue;
    }
  } else if (value is List) {
    if (value.isNotEmpty) {
      return value.first;
    } else {
      return defaultValue;
    }
  }
  return defaultValue;
}

//解密
//密钥
// ignore: non_constant_identifier_names
String AESKey = "A636B325907F1E7AB37D41D73B8A5E9F";
String decrypt(String str) {
  // log("解密前===> $str");
  String result = "";
  final key = Key.fromUtf8(AESKey);
  final encrypter = Encrypter(AES(key, mode: AESMode.ecb, padding: 'PKCS7'));
  final iv = IV.fromLength(16);
  final encrypted = Encrypted.fromBase64(str);
  try {
    result = encrypter.decrypt(
      encrypted,
      iv: iv,
    );
  } catch (e) {
    logger.e("解密错误===> $e");
  }
  // log("解密后===> $result");
  return result;
}

///加密
String encrypt(String str) {
  final key = Key.fromUtf8(AESKey);
  final iv = IV.fromLength(16);
  final encrypter = Encrypter(AES(key, mode: AESMode.ecb, padding: 'PKCS7'));
  final encrypted = encrypter.encrypt(str, iv: iv);
  return encrypted.base64;
}

String generateMD5(String data) {
  Uint8List content = const Utf8Encoder().convert(data);
  Digest digest = md5.convert(content);
  return digest.toString();
}
